//
//  ViewController.swift
//  WebViewGoback
//
//  Created by 郑东喜 on 2017/2/23.
//  Copyright © 2017年 郑东喜. All rights reserved.
//  UIwebVoew

import UIKit

 
class ViewController: UIViewController {

    lazy var webView: UIWebView = {
        let v : UIWebView = UIWebView.init(frame: self.view.bounds)
        v.delegate = self
        return v
    }()
    
    //前进
    lazy var forwardBar: UIBarButtonItem = {
        let rightBar : UIBarButtonItem = UIBarButtonItem.init(title: "前进", style: .plain, target: self, action: #selector(self.rightBarSel))
        return rightBar
    }()
    
    ///后退
    fileprivate lazy var leftBar: UIBarButtonItem = {
        let leftbar : UIBarButtonItem = UIBarButtonItem.init(title: "返回", style: .plain, target: self, action: #selector(leftBarSEL))
        return leftbar
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.prepareUI()
        self.navigationItem.leftBarButtonItem = self.leftBar
        
        self.navigationItem.rightBarButtonItem = self.forwardBar
    }
}

// MARK:- prepareUI
extension ViewController {
    /// 准备shitu
    fileprivate func prepareUI() -> Void {
        
        view.addSubview(self.webView)
        self.webView.loadRequest(URLRequest.init(url: URL.init(string: "https://www.baidu.com/")!))
    
    }
}

// MARK:- leftBar动作
extension ViewController {
    ///前进
    @objc fileprivate func rightBarSel() -> Void {
        if self.webView.canGoForward == true {
            self.webView.goForward()
        } else {}
    }
    
    @objc fileprivate func leftBarSEL() -> Void {
        if self.webView.canGoBack == true {
            self.webView.goBack()
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }

}

// MARK:- UIWebViewDelegate
extension ViewController : UIWebViewDelegate {
    func webViewDidFinishLoad(_ webView: UIWebView) {
        self.title = webView.stringByEvaluatingJavaScript(from: "document.title")
    }
}
